home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2006 December / PCWDEC06.iso / Software / Trial / Paint Shop Pro XI / Data1.cab / pdb.py.0160FC08_F3D9_4869_9D41_C611C16F42D5 < prev    next >
Encoding:
Text File  |  2005-06-08  |  34.9 KB  |  1,079 lines

  1. #! /usr/bin/env python
  2.  
  3. """A Python debugger."""
  4.  
  5. # (See pdb.doc for documentation.)
  6.  
  7. import sys
  8. import linecache
  9. import cmd
  10. import bdb
  11. from repr import Repr
  12. import os
  13. import re
  14. import pprint
  15. import traceback
  16. # Create a custom safe Repr instance and increase its maxstring.
  17. # The default of 30 truncates error messages too easily.
  18. _repr = Repr()
  19. _repr.maxstring = 200
  20. _saferepr = _repr.repr
  21.  
  22. __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
  23.            "post_mortem", "help"]
  24.  
  25. def find_function(funcname, filename):
  26.     cre = re.compile(r'def\s+%s\s*[(]' % funcname)
  27.     try:
  28.         fp = open(filename)
  29.     except IOError:
  30.         return None
  31.     # consumer of this info expects the first line to be 1
  32.     lineno = 1
  33.     answer = None
  34.     while 1:
  35.         line = fp.readline()
  36.         if line == '':
  37.             break
  38.         if cre.match(line):
  39.             answer = funcname, filename, lineno
  40.             break
  41.         lineno = lineno + 1
  42.     fp.close()
  43.     return answer
  44.  
  45.  
  46. # Interaction prompt line will separate file and call info from code
  47. # text using value of line_prefix string.  A newline and arrow may
  48. # be to your liking.  You can set it once pdb is imported using the
  49. # command "pdb.line_prefix = '\n% '".
  50. # line_prefix = ': '    # Use this to get the old situation back
  51. line_prefix = '\n-> '   # Probably a better default
  52.  
  53. class Pdb(bdb.Bdb, cmd.Cmd):
  54.  
  55.     def __init__(self):
  56.         bdb.Bdb.__init__(self)
  57.         cmd.Cmd.__init__(self)
  58.         self.prompt = '(Pdb) '
  59.         self.aliases = {}
  60.         self.mainpyfile = ''
  61.         self._wait_for_mainpyfile = 0
  62.         # Try to load readline if it exists
  63.         try:
  64.             import readline
  65.         except ImportError:
  66.             pass
  67.  
  68.         # Read $HOME/.pdbrc and ./.pdbrc
  69.         self.rcLines = []
  70.         if 'HOME' in os.environ:
  71.             envHome = os.environ['HOME']
  72.             try:
  73.                 rcFile = open(os.path.join(envHome, ".pdbrc"))
  74.             except IOError:
  75.                 pass
  76.             else:
  77.                 for line in rcFile.readlines():
  78.                     self.rcLines.append(line)
  79.                 rcFile.close()
  80.         try:
  81.             rcFile = open(".pdbrc")
  82.         except IOError:
  83.             pass
  84.         else:
  85.             for line in rcFile.readlines():
  86.                 self.rcLines.append(line)
  87.             rcFile.close()
  88.  
  89.     def reset(self):
  90.         bdb.Bdb.reset(self)
  91.         self.forget()
  92.  
  93.     def forget(self):
  94.         self.lineno = None
  95.         self.stack = []
  96.         self.curindex = 0
  97.         self.curframe = None
  98.  
  99.     def setup(self, f, t):
  100.         self.forget()
  101.         self.stack, self.curindex = self.get_stack(f, t)
  102.         self.curframe = self.stack[self.curindex][0]
  103.         self.execRcLines()
  104.  
  105.     # Can be executed earlier than 'setup' if desired
  106.     def execRcLines(self):
  107.         if self.rcLines:
  108.             # Make local copy because of recursion
  109.             rcLines = self.rcLines
  110.             # executed only once
  111.             self.rcLines = []
  112.             for line in rcLines:
  113.                 line = line[:-1]
  114.                 if len(line) > 0 and line[0] != '#':
  115.                     self.onecmd(line)
  116.  
  117.     # Override Bdb methods
  118.  
  119.     def user_call(self, frame, argument_list):
  120.         """This method is called when there is the remote possibility
  121.         that we ever need to stop in this function."""
  122.         if self._wait_for_mainpyfile:
  123.             return
  124.         if self.stop_here(frame):
  125.             print '--Call--'
  126.             self.interaction(frame, None)
  127.  
  128.     def user_line(self, frame):
  129.         """This function is called when we stop or break at this line."""
  130.         if self._wait_for_mainpyfile:
  131.             if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
  132.                 or frame.f_lineno<= 0):
  133.                 return
  134.             self._wait_for_mainpyfile = 0
  135.         self.interaction(frame, None)
  136.  
  137.     def user_return(self, frame, return_value):
  138.         """This function is called when a return trap is set here."""
  139.         frame.f_locals['__return__'] = return_value
  140.         print '--Return--'
  141.         self.interaction(frame, None)
  142.  
  143.     def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
  144.         """This function is called if an exception occurs,
  145.         but only if we are to stop at or just below this level."""
  146.         frame.f_locals['__exception__'] = exc_type, exc_value
  147.         if type(exc_type) == type(''):
  148.             exc_type_name = exc_type
  149.         else: exc_type_name = exc_type.__name__
  150.         print exc_type_name + ':', _saferepr(exc_value)
  151.         self.interaction(frame, exc_traceback)
  152.  
  153.     # General interaction function
  154.  
  155.     def interaction(self, frame, traceback):
  156.         self.setup(frame, traceback)
  157.         self.print_stack_entry(self.stack[self.curindex])
  158.         self.cmdloop()
  159.         self.forget()
  160.  
  161.     def default(self, line):
  162.         if line[:1] == '!': line = line[1:]
  163.         locals = self.curframe.f_locals
  164.         globals = self.curframe.f_globals
  165.         try:
  166.             code = compile(line + '\n', '<stdin>', 'single')
  167.             exec code in globals, locals
  168.         except:
  169.             t, v = sys.exc_info()[:2]
  170.             if type(t) == type(''):
  171.                 exc_type_name = t
  172.             else: exc_type_name = t.__name__
  173.             print '***', exc_type_name + ':', v
  174.  
  175.     def precmd(self, line):
  176.         """Handle alias expansion and ';;' separator."""
  177.         if not line.strip():
  178.             return line
  179.         args = line.split()
  180.         while args[0] in self.aliases:
  181.             line = self.aliases[args[0]]
  182.             ii = 1
  183.             for tmpArg in args[1:]:
  184.                 line = line.replace("%" + str(ii),
  185.                                       tmpArg)
  186.                 ii = ii + 1
  187.             line = line.replace("%*", ' '.join(args[1:]))
  188.             args = line.split()
  189.         # split into ';;' separated commands
  190.         # unless it's an alias command
  191.         if args[0] != 'alias':
  192.             marker = line.find(';;')
  193.             if marker >= 0:
  194.                 # queue up everything after marker
  195.                 next = line[marker+2:].lstrip()
  196.                 self.cmdqueue.append(next)
  197.                 line = line[:marker].rstrip()
  198.         return line
  199.  
  200.     # Command definitions, called by cmdloop()
  201.     # The argument is the remaining string on the command line
  202.     # Return true to exit from the command loop
  203.  
  204.     do_h = cmd.Cmd.do_help
  205.  
  206.     def do_break(self, arg, temporary = 0):
  207.         # break [ ([filename:]lineno | function) [, "condition"] ]
  208.         if not arg:
  209.             if self.breaks:  # There's at least one
  210.                 print "Num Type         Disp Enb   Where"
  211.                 for bp in bdb.Breakpoint.bpbynumber:
  212.                     if bp:
  213.                         bp.bpprint()
  214.             return
  215.         # parse arguments; comma has lowest precedence
  216.         # and cannot occur in filename
  217.         filename = None
  218.         lineno = None
  219.         cond = None
  220.         comma = arg.find(',')
  221.         if comma > 0:
  222.             # parse stuff after comma: "condition"
  223.             cond = arg[comma+1:].lstrip()
  224.             arg = arg[:comma].rstrip()
  225.         # parse stuff before comma: [filename:]lineno | function
  226.         colon = arg.rfind(':')
  227.         funcname = None
  228.         if colon >= 0:
  229.             filename = arg[:colon].rstrip()
  230.             f = self.lookupmodule(filename)
  231.             if not f:
  232.                 print '*** ', repr(filename),
  233.                 print 'not found from sys.path'
  234.                 return
  235.             else:
  236.                 filename = f
  237.             arg = arg[colon+1:].lstrip()
  238.             try:
  239.                 lineno = int(arg)
  240.             except ValueError, msg:
  241.                 print '*** Bad lineno:', arg
  242.                 return
  243.         else:
  244.             # no colon; can be lineno or function
  245.             try:
  246.                 lineno = int(arg)
  247.             except ValueError:
  248.                 try:
  249.                     func = eval(arg,
  250.                                 self.curframe.f_globals,
  251.                                 self.curframe.f_locals)
  252.                 except:
  253.                     func = arg
  254.                 try:
  255.                     if hasattr(func, 'im_func'):
  256.                         func = func.im_func
  257.                     code = func.func_code
  258.                     #use co_name to identify the bkpt (function names
  259.                     #could be aliased, but co_name is invariant)
  260.                     funcname = code.co_name
  261.                     lineno = code.co_firstlineno
  262.                     filename = code.co_filename
  263.                 except:
  264.                     # last thing to try
  265.                     (ok, filename, ln) = self.lineinfo(arg)
  266.                     if not ok:
  267.                         print '*** The specified object',
  268.                         print repr(arg),
  269.                         print 'is not a function'
  270.                         print ('or was not found '
  271.                                'along sys.path.')
  272.                         return
  273.                     funcname = ok # ok contains a function name
  274.                     lineno = int(ln)
  275.         if not filename:
  276.             filename = self.defaultFile()
  277.         # Check for reasonable breakpoint
  278.         line = self.checkline(filename, lineno)
  279.         if line:
  280.             # now set the break point
  281.             err = self.set_break(filename, line, temporary, cond, funcname)
  282.             if err: print '***', err
  283.             else:
  284.                 bp = self.get_breaks(filename, line)[-1]
  285.                 print "Breakpoint %d at %s:%d" % (bp.number,
  286.                                                   bp.file,
  287.                                                   bp.line)
  288.  
  289.     # To be overridden in derived debuggers
  290.     def defaultFile(self):
  291.         """Produce a reasonable default."""
  292.         filename = self.curframe.f_code.co_filename
  293.         if filename == '<string>' and self.mainpyfile:
  294.             filename = self.mainpyfile
  295.         return filename
  296.  
  297.     do_b = do_break
  298.  
  299.     def do_tbreak(self, arg):
  300.         self.do_break(arg, 1)
  301.  
  302.     def lineinfo(self, identifier):
  303.         failed = (None, None, None)
  304.         # Input is identifier, may be in single quotes
  305.         idstring = identifier.split("'")
  306.         if len(idstring) == 1:
  307.             # not in single quotes
  308.             id = idstring[0].strip()
  309.         elif len(idstring) == 3:
  310.             # quoted
  311.             id = idstring[1].strip()
  312.         else:
  313.             return failed
  314.         if id == '': return failed
  315.         parts = id.split('.')
  316.         # Protection for derived debuggers
  317.         if parts[0] == 'self':
  318.             del parts[0]
  319.             if len(parts) == 0:
  320.                 return failed
  321.         # Best first guess at file to look at
  322.         fname = self.defaultFile()
  323.         if len(parts) == 1:
  324.             item = parts[0]
  325.         else:
  326.             # More than one part.
  327.             # First is module, second is method/class
  328.             f = self.lookupmodule(parts[0])
  329.             if f:
  330.                 fname = f
  331.             item = parts[1]
  332.         answer = find_function(item, fname)
  333.         return answer or failed
  334.  
  335.     def checkline(self, filename, lineno):
  336.         """Check whether specified line seems to be executable.
  337.  
  338.         Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
  339.         line or EOF). Warning: testing is not comprehensive.
  340.         """
  341.         line = linecache.getline(filename, lineno)
  342.         if not line:
  343.             print 'End of file'
  344.             return 0
  345.         line = line.strip()
  346.         # Don't allow setting breakpoint at a blank line
  347.         if (not line or (line[0] == '#') or
  348.              (line[:3] == '"""') or line[:3] == "'''"):
  349.             print '*** Blank or comment'
  350.             return 0
  351.         return lineno
  352.  
  353.     def do_enable(self, arg):
  354.         args = arg.split()
  355.         for i in args:
  356.             try:
  357.                 i = int(i)
  358.             except ValueError:
  359.                 print 'Breakpoint index %r is not a number' % i
  360.                 continue
  361.  
  362.             if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
  363.                 print 'No breakpoint numbered', i
  364.                 continue
  365.  
  366.             bp = bdb.Breakpoint.bpbynumber[i]
  367.             if bp:
  368.                 bp.enable()
  369.  
  370.     def do_disable(self, arg):
  371.         args = arg.split()
  372.         for i in args:
  373.             try:
  374.                 i = int(i)
  375.             except ValueError:
  376.                 print 'Breakpoint index %r is not a number' % i
  377.                 continue
  378.  
  379.             if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
  380.                 print 'No breakpoint numbered', i
  381.                 continue
  382.  
  383.             bp = bdb.Breakpoint.bpbynumber[i]
  384.             if bp:
  385.                 bp.disable()
  386.  
  387.     def do_condition(self, arg):
  388.         # arg is breakpoint number and condition
  389.         args = arg.split(' ', 1)
  390.         bpnum = int(args[0].strip())
  391.         try:
  392.             cond = args[1]
  393.         except:
  394.             cond = None
  395.         bp = bdb.Breakpoint.bpbynumber[bpnum]
  396.         if bp:
  397.             bp.cond = cond
  398.             if not cond:
  399.                 print 'Breakpoint', bpnum,
  400.                 print 'is now unconditional.'
  401.  
  402.     def do_ignore(self,arg):
  403.         """arg is bp number followed by ignore count."""
  404.         args = arg.split()
  405.         bpnum = int(args[0].strip())
  406.         try:
  407.             count = int(args[1].strip())
  408.         except:
  409.             count = 0
  410.         bp = bdb.Breakpoint.bpbynumber[bpnum]
  411.         if bp:
  412.             bp.ignore = count
  413.             if count > 0:
  414.                 reply = 'Will ignore next '
  415.                 if count > 1:
  416.                     reply = reply + '%d crossings' % count
  417.                 else:
  418.                     reply = reply + '1 crossing'
  419.                 print reply + ' of breakpoint %d.' % bpnum
  420.             else:
  421.                 print 'Will stop next time breakpoint',
  422.                 print bpnum, 'is reached.'
  423.  
  424.     def do_clear(self, arg):
  425.         """Three possibilities, tried in this order:
  426.         clear -> clear all breaks, ask for confirmation
  427.         clear file:lineno -> clear all breaks at file:lineno
  428.         clear bpno bpno ... -> clear breakpoints by number"""
  429.         if not arg:
  430.             try:
  431.                 reply = raw_input('Clear all breaks? ')
  432.             except EOFError:
  433.                 reply = 'no'
  434.             reply = reply.strip().lower()
  435.             if reply in ('y', 'yes'):
  436.                 self.clear_all_breaks()
  437.             return
  438.         if ':' in arg:
  439.             # Make sure it works for "clear C:\foo\bar.py:12"
  440.             i = arg.rfind(':')
  441.             filename = arg[:i]
  442.             arg = arg[i+1:]
  443.             try:
  444.                 lineno = int(arg)
  445.             except:
  446.                 err = "Invalid line number (%s)" % arg
  447.             else:
  448.                 err = self.clear_break(filename, lineno)
  449.             if err: print '***', err
  450.             return
  451.         numberlist = arg.split()
  452.         for i in numberlist:
  453.             err = self.clear_bpbynumber(i)
  454.             if err:
  455.                 print '***', err
  456.             else:
  457.                 print 'Deleted breakpoint %s ' % (i,)
  458.     do_cl = do_clear # 'c' is already an abbreviation for 'continue'
  459.  
  460.     def do_where(self, arg):
  461.         self.print_stack_trace()
  462.     do_w = do_where
  463.     do_bt = do_where
  464.  
  465.     def do_up(self, arg):
  466.         if self.curindex == 0:
  467.             print '*** Oldest frame'
  468.         else:
  469.             self.curindex = self.curindex - 1
  470.             self.curframe = self.stack[self.curindex][0]
  471.             self.print_stack_entry(self.stack[self.curindex])
  472.             self.lineno = None
  473.     do_u = do_up
  474.  
  475.     def do_down(self, arg):
  476.         if self.curindex + 1 == len(self.stack):
  477.             print '*** Newest frame'
  478.         else:
  479.             self.curindex = self.curindex + 1
  480.             self.curframe = self.stack[self.curindex][0]
  481.             self.print_stack_entry(self.stack[self.curindex])
  482.             self.lineno = None
  483.     do_d = do_down
  484.  
  485.     def do_step(self, arg):
  486.         self.set_step()
  487.         return 1
  488.     do_s = do_step
  489.  
  490.     def do_next(self, arg):
  491.         self.set_next(self.curframe)
  492.         return 1
  493.     do_n = do_next
  494.  
  495.     def do_return(self, arg):
  496.         self.set_return(self.curframe)
  497.         return 1
  498.     do_r = do_return
  499.  
  500.     def do_continue(self, arg):
  501.         self.set_continue()
  502.         return 1
  503.     do_c = do_cont = do_continue
  504.  
  505.     def do_jump(self, arg):
  506.         if self.curindex + 1 != len(self.stack):
  507.             print "*** You can only jump within the bottom frame"
  508.             return
  509.         try:
  510.             arg = int(arg)
  511.         except ValueError:
  512.             print "*** The 'jump' command requires a line number."
  513.         else:
  514.             try:
  515.                 # Do the jump, fix up our copy of the stack, and display the
  516.                 # new position
  517.                 self.curframe.f_lineno = arg
  518.                 self.stack[self.curindex] = self.stack[self.curindex][0], arg
  519.                 self.print_stack_entry(self.stack[self.curindex])
  520.             except ValueError, e:
  521.                 print '*** Jump failed:', e
  522.     do_j = do_jump
  523.  
  524.     def do_debug(self, arg):
  525.         sys.settrace(None)
  526.         globals = self.curframe.f_globals
  527.         locals = self.curframe.f_locals
  528.         p = Pdb()
  529.         p.prompt = "(%s) " % self.prompt.strip()
  530.         print "ENTERING RECURSIVE DEBUGGER"
  531.         sys.call_tracing(p.run, (arg, globals, locals))
  532.         print "LEAVING RECURSIVE DEBUGGER"
  533.         sys.settrace(self.trace_dispatch)
  534.         self.lastcmd = p.lastcmd
  535.  
  536.     def do_quit(self, arg):
  537.         self._user_requested_quit = 1
  538.         self.set_quit()
  539.         return 1
  540.  
  541.     do_q = do_quit
  542.     do_exit = do_quit
  543.  
  544.     def do_EOF(self, arg):
  545.         print
  546.         self._user_requested_quit = 1
  547.         self.set_quit()
  548.         return 1
  549.  
  550.     def do_args(self, arg):
  551.         f = self.curframe
  552.         co = f.f_code
  553.         dict = f.f_locals
  554.         n = co.co_argcount
  555.         if co.co_flags & 4: n = n+1
  556.         if co.co_flags & 8: n = n+1
  557.         for i in range(n):
  558.             name = co.co_varnames[i]
  559.             print name, '=',
  560.             if name in dict: print dict[name]
  561.             else: print "*** undefined ***"
  562.     do_a = do_args
  563.  
  564.     def do_retval(self, arg):
  565.         if '__return__' in self.curframe.f_locals:
  566.             print self.curframe.f_locals['__return__']
  567.         else:
  568.             print '*** Not yet returned!'
  569.     do_rv = do_retval
  570.  
  571.     def _getval(self, arg):
  572.         try:
  573.             return eval(arg, self.curframe.f_globals,
  574.                         self.curframe.f_locals)
  575.         except:
  576.             t, v = sys.exc_info()[:2]
  577.             if isinstance(t, str):
  578.                 exc_type_name = t
  579.             else: exc_type_name = t.__name__
  580.             print '***', exc_type_name + ':', repr(v)
  581.             raise
  582.  
  583.     def do_p(self, arg):
  584.         try:
  585.             print repr(self._getval(arg))
  586.         except:
  587.             pass
  588.  
  589.     def do_pp(self, arg):
  590.         try:
  591.             pprint.pprint(self._getval(arg))
  592.         except:
  593.             pass
  594.  
  595.     def do_list(self, arg):
  596.         self.lastcmd = 'list'
  597.         last = None
  598.         if arg:
  599.             try:
  600.                 x = eval(arg, {}, {})
  601.                 if type(x) == type(()):
  602.                     first, last = x
  603.                     first = int(first)
  604.                     last = int(last)
  605.                     if last < first:
  606.                         # Assume it's a count
  607.                         last = first + last
  608.                 else:
  609.                     first = max(1, int(x) - 5)
  610.             except:
  611.                 print '*** Error in argument:', repr(arg)
  612.                 return
  613.         elif self.lineno is None:
  614.             first = max(1, self.curframe.f_lineno - 5)
  615.         else:
  616.             first = self.lineno + 1
  617.         if last is None:
  618.             last = first + 10
  619.         filename = self.curframe.f_code.co_filename
  620.         breaklist = self.get_file_breaks(filename)
  621.         try:
  622.             for lineno in range(first, last+1):
  623.                 line = linecache.getline(filename, lineno)
  624.                 if not line:
  625.                     print '[EOF]'
  626.                     break
  627.                 else:
  628.                     s = repr(lineno).rjust(3)
  629.                     if len(s) < 4: s = s + ' '
  630.                     if lineno in breaklist: s = s + 'B'
  631.                     else: s = s + ' '
  632.                     if lineno == self.curframe.f_lineno:
  633.                         s = s + '->'
  634.                     print s + '\t' + line,
  635.                     self.lineno = lineno
  636.         except KeyboardInterrupt:
  637.             pass
  638.     do_l = do_list
  639.  
  640.     def do_whatis(self, arg):
  641.         try:
  642.             value = eval(arg, self.curframe.f_globals,
  643.                             self.curframe.f_locals)
  644.         except:
  645.             t, v = sys.exc_info()[:2]
  646.             if type(t) == type(''):
  647.                 exc_type_name = t
  648.             else: exc_type_name = t.__name__
  649.             print '***', exc_type_name + ':', repr(v)
  650.             return
  651.         code = None
  652.         # Is it a function?
  653.         try: code = value.func_code
  654.         except: pass
  655.         if code:
  656.             print 'Function', code.co_name
  657.             return
  658.         # Is it an instance method?
  659.         try: code = value.im_func.func_code
  660.         except: pass
  661.         if code:
  662.             print 'Method', code.co_name
  663.             return
  664.         # None of the above...
  665.         print type(value)
  666.  
  667.     def do_alias(self, arg):
  668.         args = arg.split()
  669.         if len(args) == 0:
  670.             keys = self.aliases.keys()
  671.             keys.sort()
  672.             for alias in keys:
  673.                 print "%s = %s" % (alias, self.aliases[alias])
  674.             return
  675.         if args[0] in self.aliases and len(args) == 1:
  676.             print "%s = %s" % (args[0], self.aliases[args[0]])
  677.         else:
  678.             self.aliases[args[0]] = ' '.join(args[1:])
  679.  
  680.     def do_unalias(self, arg):
  681.         args = arg.split()
  682.         if len(args) == 0: return
  683.         if args[0] in self.aliases:
  684.             del self.aliases[args[0]]
  685.  
  686.     # Print a traceback starting at the top stack frame.
  687.     # The most recently entered frame is printed last;
  688.     # this is different from dbx and gdb, but consistent with
  689.     # the Python interpreter's stack trace.
  690.     # It is also consistent with the up/down commands (which are
  691.     # compatible with dbx and gdb: up moves towards 'main()'
  692.     # and down moves towards the most recent stack frame).
  693.  
  694.     def print_stack_trace(self):
  695.         try:
  696.             for frame_lineno in self.stack:
  697.                 self.print_stack_entry(frame_lineno)
  698.         except KeyboardInterrupt:
  699.             pass
  700.  
  701.     def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
  702.         frame, lineno = frame_lineno
  703.         if frame is self.curframe:
  704.             print '>',
  705.         else:
  706.             print ' ',
  707.         print self.format_stack_entry(frame_lineno, prompt_prefix)
  708.  
  709.  
  710.     # Help methods (derived from pdb.doc)
  711.  
  712.     def help_help(self):
  713.         self.help_h()
  714.  
  715.     def help_h(self):
  716.         print """h(elp)
  717. Without argument, print the list of available commands.
  718. With a command name as argument, print help about that command
  719. "help pdb" pipes the full documentation file to the $PAGER
  720. "help exec" gives help on the ! command"""
  721.  
  722.     def help_where(self):
  723.         self.help_w()
  724.  
  725.     def help_w(self):
  726.         print """w(here)
  727. Print a stack trace, with the most recent frame at the bottom.
  728. An arrow indicates the "current frame", which determines the
  729. context of most commands.  'bt' is an alias for this command."""
  730.  
  731.     help_bt = help_w
  732.  
  733.     def help_down(self):
  734.         self.help_d()
  735.  
  736.     def help_d(self):
  737.         print """d(own)
  738. Move the current frame one level down in the stack trace
  739. (to a newer frame)."""
  740.  
  741.     def help_up(self):
  742.         self.help_u()
  743.  
  744.     def help_u(self):
  745.         print """u(p)
  746. Move the current frame one level up in the stack trace
  747. (to an older frame)."""
  748.  
  749.     def help_break(self):
  750.         self.help_b()
  751.  
  752.     def help_b(self):
  753.         print """b(reak) ([file:]lineno | function) [, condition]
  754. With a line number argument, set a break there in the current
  755. file.  With a function name, set a break at first executable line
  756. of that function.  Without argument, list all breaks.  If a second
  757. argument is present, it is a string specifying an expression
  758. which must evaluate to true before the breakpoint is honored.
  759.  
  760. The line number may be prefixed with a filename and a colon,
  761. to specify a breakpoint in another file (probably one that
  762. hasn't been loaded yet).  The file is searched for on sys.path;
  763. the .py suffix may be omitted."""
  764.  
  765.     def help_clear(self):
  766.         self.help_cl()
  767.  
  768.     def help_cl(self):
  769.         print "cl(ear) filename:lineno"
  770.         print """cl(ear) [bpnumber [bpnumber...]]
  771. With a space separated list of breakpoint numbers, clear
  772. those breakpoints.  Without argument, clear all breaks (but
  773. first ask confirmation).  With a filename:lineno argument,
  774. clear all breaks at that line in that file.
  775.  
  776. Note that the argument is different from previous versions of
  777. the debugger (in python distributions 1.5.1 and before) where
  778. a linenumber was used instead of either filename:lineno or
  779. breakpoint numbers."""
  780.  
  781.     def help_tbreak(self):
  782.         print """tbreak  same arguments as break, but breakpoint is
  783. removed when first hit."""
  784.  
  785.     def help_enable(self):
  786.         print """enable bpnumber [bpnumber ...]
  787. Enables the breakpoints given as a space separated list of
  788. bp numbers."""
  789.  
  790.     def help_disable(self):
  791.         print """disable bpnumber [bpnumber ...]
  792. Disables the breakpoints given as a space separated list of
  793. bp numbers."""
  794.  
  795.     def help_ignore(self):
  796.         print """ignore bpnumber count
  797. Sets the ignore count for the given breakpoint number.  A breakpoint
  798. becomes active when the ignore count is zero.  When non-zero, the
  799. count is decremented each time the breakpoint is reached and the
  800. breakpoint is not disabled and any associated condition evaluates
  801. to true."""
  802.  
  803.     def help_condition(self):
  804.         print """condition bpnumber str_condition
  805. str_condition is a string specifying an expression which
  806. must evaluate to true before the breakpoint is honored.
  807. If str_condition is absent, any existing condition is removed;
  808. i.e., the breakpoint is made unconditional."""
  809.  
  810.     def help_step(self):
  811.         self.help_s()
  812.  
  813.     def help_s(self):
  814.         print """s(tep)
  815. Execute the current line, stop at the first possible occasion
  816. (either in a function that is called or in the current function)."""
  817.  
  818.     def help_next(self):
  819.         self.help_n()
  820.  
  821.     def help_n(self):
  822.         print """n(ext)
  823. Continue execution until the next line in the current function
  824. is reached or it returns."""
  825.  
  826.     def help_return(self):
  827.         self.help_r()
  828.  
  829.     def help_r(self):
  830.         print """r(eturn)
  831. Continue execution until the current function returns."""
  832.  
  833.     def help_continue(self):
  834.         self.help_c()
  835.  
  836.     def help_cont(self):
  837.         self.help_c()
  838.  
  839.     def help_c(self):
  840.         print """c(ont(inue))
  841. Continue execution, only stop when a breakpoint is encountered."""
  842.  
  843.     def help_jump(self):
  844.         self.help_j()
  845.  
  846.     def help_j(self):
  847.         print """j(ump) lineno
  848. Set the next line that will be executed."""
  849.  
  850.     def help_debug(self):
  851.         print """debug code
  852. Enter a recursive debugger that steps through the code argument
  853. (which is an arbitrary expression or statement to be executed
  854. in the current environment)."""
  855.  
  856.     def help_list(self):
  857.         self.help_l()
  858.  
  859.     def help_l(self):
  860.         print """l(ist) [first [,last]]
  861. List source code for the current file.
  862. Without arguments, list 11 lines around the current line
  863. or continue the previous listing.
  864. With one argument, list 11 lines starting at that line.
  865. With two arguments, list the given range;
  866. if the second argument is less than the first, it is a count."""
  867.  
  868.     def help_args(self):
  869.         self.help_a()
  870.  
  871.     def help_a(self):
  872.         print """a(rgs)
  873. Print the arguments of the current function."""
  874.  
  875.     def help_p(self):
  876.         print """p expression
  877. Print the value of the expression."""
  878.  
  879.     def help_pp(self):
  880.         print """pp expression
  881. Pretty-print the value of the expression."""
  882.  
  883.     def help_exec(self):
  884.         print """(!) statement
  885. Execute the (one-line) statement in the context of
  886. the current stack frame.
  887. The exclamation point can be omitted unless the first word
  888. of the statement resembles a debugger command.
  889. To assign to a global variable you must always prefix the
  890. command with a 'global' command, e.g.:
  891. (Pdb) global list_options; list_options = ['-l']
  892. (Pdb)"""
  893.  
  894.     def help_quit(self):
  895.         self.help_q()
  896.  
  897.     def help_q(self):
  898.         print """q(uit) or exit - Quit from the debugger.
  899. The program being executed is aborted."""
  900.  
  901.     help_exit = help_q
  902.  
  903.     def help_whatis(self):
  904.         print """whatis arg
  905. Prints the type of the argument."""
  906.  
  907.     def help_EOF(self):
  908.         print """EOF
  909. Handles the receipt of EOF as a command."""
  910.  
  911.     def help_alias(self):
  912.         print """alias [name [command [parameter parameter ...] ]]
  913. Creates an alias called 'name' the executes 'command'.  The command
  914. must *not* be enclosed in quotes.  Replaceable parameters are
  915. indicated by %1, %2, and so on, while %* is replaced by all the
  916. parameters.  If no command is given, the current alias for name
  917. is shown. If no name is given, all aliases are listed.
  918.  
  919. Aliases may be nested and can contain anything that can be
  920. legally typed at the pdb prompt.  Note!  You *can* override
  921. internal pdb commands with aliases!  Those internal commands
  922. are then hidden until the alias is removed.  Aliasing is recursively
  923. applied to the first word of the command line; all other words
  924. in the line are left alone.
  925.  
  926. Some useful aliases (especially when placed in the .pdbrc file) are:
  927.  
  928. #Print instance variables (usage "pi classInst")
  929. alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
  930.  
  931. #Print instance variables in self
  932. alias ps pi self
  933. """
  934.  
  935.     def help_unalias(self):
  936.         print """unalias name
  937. Deletes the specified alias."""
  938.  
  939.     def help_pdb(self):
  940.         help()
  941.  
  942.     def lookupmodule(self, filename):
  943.         """Helper function for break/clear parsing -- may be overridden.
  944.  
  945.         lookupmodule() translates (possibly incomplete) file or module name
  946.         into an absolute file name.
  947.         """
  948.         if os.path.isabs(filename) and  os.path.exists(filename):
  949.             return filename
  950.         f = os.path.join(sys.path[0], filename)
  951.         if  os.path.exists(f) and self.canonic(f) == self.mainpyfile:
  952.             return f
  953.         root, ext = os.path.splitext(filename)
  954.         if ext == '':
  955.             filename = filename + '.py'
  956.         if os.path.isabs(filename):
  957.             return filename
  958.         for dirname in sys.path:
  959.             while os.path.islink(dirname):
  960.                 dirname = os.readlink(dirname)
  961.             fullname = os.path.join(dirname, filename)
  962.             if os.path.exists(fullname):
  963.                 return fullname
  964.         return None
  965.  
  966.     def _runscript(self, filename):
  967.         # Start with fresh empty copy of globals and locals and tell the script
  968.         # that it's being run as __main__ to avoid scripts being able to access
  969.         # the pdb.py namespace.
  970.         globals_ = {"__name__" : "__main__"}
  971.         locals_ = globals_
  972.  
  973.         # When bdb sets tracing, a number of call and line events happens
  974.         # BEFORE debugger even reaches user's code (and the exact sequence of
  975.         # events depends on python version). So we take special measures to
  976.         # avoid stopping before we reach the main script (see user_line and
  977.         # user_call for details).
  978.         self._wait_for_mainpyfile = 1
  979.         self.mainpyfile = self.canonic(filename)
  980.         self._user_requested_quit = 0
  981.         statement = 'execfile( "%s")' % filename
  982.         self.run(statement, globals=globals_, locals=locals_)
  983.  
  984. # Simplified interface
  985.  
  986. def run(statement, globals=None, locals=None):
  987.     Pdb().run(statement, globals, locals)
  988.  
  989. def runeval(expression, globals=None, locals=None):
  990.     return Pdb().runeval(expression, globals, locals)
  991.  
  992. def runctx(statement, globals, locals):
  993.     # B/W compatibility
  994.     run(statement, globals, locals)
  995.  
  996. def runcall(*args, **kwds):
  997.     return Pdb().runcall(*args, **kwds)
  998.  
  999. def set_trace():
  1000.     Pdb().set_trace(sys._getframe().f_back)
  1001.  
  1002. # Post-Mortem interface
  1003.  
  1004. def post_mortem(t):
  1005.     p = Pdb()
  1006.     p.reset()
  1007.     while t.tb_next is not None:
  1008.         t = t.tb_next
  1009.     p.interaction(t.tb_frame, t)
  1010.  
  1011. def pm():
  1012.     post_mortem(sys.last_traceback)
  1013.  
  1014.  
  1015. # Main program for testing
  1016.  
  1017. TESTCMD = 'import x; x.main()'
  1018.  
  1019. def test():
  1020.     run(TESTCMD)
  1021.  
  1022. # print help
  1023. def help():
  1024.     for dirname in sys.path:
  1025.         fullname = os.path.join(dirname, 'pdb.doc')
  1026.         if os.path.exists(fullname):
  1027.             sts = os.system('${PAGER-more} '+fullname)
  1028.             if sts: print '*** Pager exit status:', sts
  1029.             break
  1030.     else:
  1031.         print 'Sorry, can\'t find the help file "pdb.doc"',
  1032.         print 'along the Python search path'
  1033.  
  1034. def main():
  1035.     if not sys.argv[1:]:
  1036.         print "usage: pdb.py scriptfile [arg] ..."
  1037.         sys.exit(2)
  1038.  
  1039.     mainpyfile =  sys.argv[1]     # Get script filename
  1040.     if not os.path.exists(mainpyfile):
  1041.         print 'Error:', mainpyfile, 'does not exist'
  1042.         sys.exit(1)
  1043.  
  1044.     del sys.argv[0]         # Hide "pdb.py" from argument list
  1045.  
  1046.     # Replace pdb's dir with script's dir in front of module search path.
  1047.     sys.path[0] = os.path.dirname(mainpyfile)
  1048.  
  1049.     # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
  1050.     # modified by the script being debugged. It's a bad idea when it was
  1051.     # changed by the user from the command line. The best approach would be to
  1052.     # have a "restart" command which would allow explicit specification of
  1053.     # command line arguments.
  1054.     pdb = Pdb()
  1055.     while 1:
  1056.         try:
  1057.             pdb._runscript(mainpyfile)
  1058.             if pdb._user_requested_quit:
  1059.                 break
  1060.             print "The program finished and will be restarted"
  1061.         except SystemExit:
  1062.             # In most cases SystemExit does not warrant a post-mortem session.
  1063.             print "The program exited via sys.exit(). Exit status: ",
  1064.             print sys.exc_info()[1]
  1065.         except:
  1066.             traceback.print_exc()
  1067.             print "Uncaught exception. Entering post mortem debugging"
  1068.             print "Running 'cont' or 'step' will restart the program"
  1069.             t = sys.exc_info()[2]
  1070.             while t.tb_next is not None:
  1071.                 t = t.tb_next
  1072.             pdb.interaction(t.tb_frame,t)
  1073.             print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
  1074.  
  1075.  
  1076. # When invoked as main program, invoke the debugger on a script
  1077. if __name__=='__main__':
  1078.     main()
  1079.